using System.Text;
using System.Xml;
using SharpObjects.Logging;
using SharpObjects.Configuration;
using SharpObjects.Configuration.ConfigurationProviders;
using SharpObjects.Logging.Utils;

namespace SharpObjects.Logging.Formatters
{
	public class XmlLogFormatter : LogFormatterBase, ILogFormatter
	{
		new public abstract class Tags : LogFormatterBase.Tags
		{
			public const string timeFormat = "time_format";
		}

		protected string timeFormat = "G";

		public XmlLogFormatter()
		{
			this.MessageSeparator = string.Empty;
			this.ValueDelimiter = string.Empty;
		}


		//#region ILogFormatter Members

		public override string ApplyFormat(ILogEntry logEntry)
		{
			StringBuilder sb = new StringBuilder();

			sb.Append("<log_entry>");
			sb.Append("<time>");
			sb.Append(logEntry.Time.ToString(this.timeFormat));
			sb.Append("</time><category>");
			sb.Append(logEntry.Category);
			sb.Append("</category><origin>");
			sb.Append(logEntry.Origin);
			sb.Append("</origin><machine_name>");
			sb.Append(logEntry.MachineName);
			sb.Append("</machine_name>");
			
			if(ProcessInformation.UseProcessInfo)
			{
				sb.Append("<process_name>");
				sb.Append(logEntry.ProcessName);
				sb.Append("</process_name><process_id>");
				sb.Append(logEntry.ProcessId.ToString());
				sb.Append("</process_id>");
			}
			else
			{
				sb.Append("<process_name>");
				sb.Append("</process_name><process_id>");
				sb.Append("</process_id>");
			}
			
			sb.Append("<thread_id>");
			sb.Append(logEntry.ThreadId);
			sb.Append("</thread_id><thread_name>");
			sb.Append(logEntry.ThreadName);
			sb.Append("</thread_name>");
			sb.Append("<message><![CDATA[");
			sb.Append(logEntry.Message);
			sb.Append("]]></message>");
			sb.Append("<stack_trace><![CDATA[");
			sb.Append(logEntry.StackTrace);
			sb.Append("]]></stack_trace></log_entry>");
			sb.Append("\r\n");

			return sb.ToString();
		}



		//#endregion
			
		public override void Initialize(XmlElement initializationElement)
		{
			base.Initialize (initializationElement);

			IConfigurationReader config = new XmlConfigurationProvider(initializationElement);
			this.timeFormat = config.GetString(Tags.timeFormat, this.timeFormat);

		}
	
	}
}


